package com.book.bookmanager.controller;

import com.book.bookmanager.pojo.User;
import com.book.bookmanager.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class userController {
	/**
	 * controller层调用service层，创建service对象
	 */
	@Autowired
	private userService us;

	/**
	 * 登录
	 */
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "login";
	}

	@RequestMapping("/loginSuccess")
	public String loginSuccess(Model model, User user, HttpSession session) {
		/**
		 * 查询用户是否存在
		 */
		try {
			User user1 = us.queryByUser(user.getUser());
			System.out.println(user1);
			if (user1 != null) {
				if (user1.getPassword().equals(user.getPassword())) {
					String user2 = user1.getUser();
					System.out.println(user1.toString());
					session.setAttribute("user", user2);
					return "redirect:/book/queryAll";
				} else {
					model.addAttribute("data", "密码不正确");
					return "login";
				}

			} else {
				/**
				 * 用户不存在跳转登录
				 */
				model.addAttribute("data", "该用户不存在，请先注册");
				return "login";
			}

		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}


	/**
	 * 注册
	 */
	@RequestMapping("/toRegister")
	public String toRegister() {
		return "register";
	}

	@RequestMapping("/toRegisterSuccess")
	public String toRegisterSuccess(Model model, User user) {
		/**
		 * 添加信息到数据库
		 */
		try {
			User userName = us.queryByUser(user.getUser());
			/**
			 * 没有用户可以进行注册
			 */
			if (userName == null) {
				int add = us.add(user);
				System.out.println("插入数据成功");
				model.addAttribute("data", "注册成功，请登录");
				return "login";
			} else {
				model.addAttribute("data", "用户名重复，请重新注册");
				return "register";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}

	}
}
